package com.travelsky.flash.util.msg;

import java.io.IOException;
import java.util.ArrayList;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.apache.log4j.Logger;

/**
 * @Description websocket 消息推送服务器
 * @author syuan
 * @date 2015年6月1日  下午4:53:38
 * Company: TravelSky
 */
@ServerEndpoint("/msgServer")
public class WebSocketServer{

	private static Logger logger = Logger.getLogger(WebSocketServer.class);
	
	private static final ArrayList<Session> sessions;

	static {
		sessions = new ArrayList<Session>();
	}

	@OnOpen
	public void onOpen(Session session) {
		logger.info("----------------session open:"+session.getId()+"-----------");
		sessions.add(session);
	}

	@OnMessage
	public void onMessage(String message) {
//		logger.info("------------server new msg: "+message +"-----------");
		sendMessage(message);
	}

	@OnClose
	public void onClose(Session session) {
		logger.info("----------------client close"+session.getId()+"--------------");
		sessions.remove(session);
	}

	public void sendMessage(String message) {
		for (Session session : sessions) {
			try {
				session.getBasicRemote().sendText(message);
			} catch (IOException e) {
				logger.error("", e);
			}
		}
	}

}
